package com.community.common.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.common.mapper.OwnerHouseMapper;
import com.community.common.mapper.UserPermissionMapper;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.Picture;
import com.community.common.pojo.domain.PublicUser;
import com.community.common.pojo.dto.BindToWxDto;
import com.community.common.pojo.dto.FindOwnerDto;
import com.community.common.pojo.dto.PublicUserCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.LayuiPage;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.PublicUserVo;
import com.community.common.pojo.vo.UserPermissionDto;
import com.community.common.pojo.vo.WXPublicUserVo;
import com.community.common.service.ManagerUserService;
import com.community.common.service.PictureService;
import com.community.common.service.PublicUserService;
import com.community.common.service.UserPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 公众号用户表 前端控制器
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@RestController
@RequestMapping("/publicUser")
@Slf4j
public class PublicUserController {

    @Resource
    private ManagerUserService managerUserService;
    @Autowired
    private PublicUserService publicUserService;
    @Autowired
    private PictureService pictureService;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private UserPermissionService userPermissionService;
    @Autowired
    private OwnerHouseMapper ownerHouseMapper;

    @PostMapping("/delRec")
    public MyResponse delRec(String ids) {
        //“,”分割成数组
        String[] strIds = ids.split(",");
        if (null != strIds && strIds.length > 0) {
            for (String id : strIds) {
                if (ownerHouseMapper.deleteById(id)<0){
                    return MyResponse.fail();
                }
            }
        }
        return MyResponse.success();
    }
    /**
     * @return 查询当前小区所有待审核用户
     */
    @PostMapping("/queryAudit")
    public LayuiPage queryAudit(@RequestBody PageRequest<PublicUserCondition> publicUserConditionPageRequest, HttpSession session) {
        List<PublicUserVo> publicUserVos = publicUserService.queryByPageAll(publicUserConditionPageRequest,
                managerUserService.getCommunityIdFromSession(session), "0");
        return LayuiPage.parsePage(publicUserVos);
    }

    /**
     * @return 查询当前小区所有 审核通过
     */
    @PostMapping("/queryPass")
    public LayuiPage queryPass(@RequestBody PageRequest<PublicUserCondition> publicUserConditionPageRequest, HttpSession session) {
        List<PublicUserVo> publicUserVos = publicUserService.queryByPageAll(publicUserConditionPageRequest,
                managerUserService.getCommunityIdFromSession(session), "1");
        return LayuiPage.parsePage(publicUserVos);
    }

    /**
     * @return 查询当前小区所有 审核不通过
     */
    @PostMapping("/queryNoPass")
    public LayuiPage queryNoPass(@RequestBody PageRequest<PublicUserCondition> publicUserConditionPageRequest, HttpSession session) {
        List<PublicUserVo> publicUserVos = publicUserService.queryByPageAll(publicUserConditionPageRequest,
                managerUserService.getCommunityIdFromSession(session), "2");
        return LayuiPage.parsePage(publicUserVos);
    }

    /**
     * fixme 黑名单功能暂时废弃
     *
     * @return 用户管理tab里查询所有用户
     */
    @PostMapping("/queryByPageBlack")
    public LayuiPage queryByPageBlack(@RequestBody PageRequest<PublicUserCondition> publicUserConditionPageRequest, HttpSession session) {
        List<PublicUserVo> publicUserVos = publicUserService.queryByPageBlack(publicUserConditionPageRequest,
                managerUserService.getCommunityIdFromSession(session));
        return LayuiPage.parsePage(publicUserVos);
    }

    //用户新增
    @PostMapping("/save")
    public MyResponse save(@Valid @RequestBody WXPublicUserVo wxPublicUserVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return publicUserService.saveUser(wxPublicUserVo);
    }

    //用户修改
    @PutMapping("/update")
    public MyResponse update(@Valid @RequestBody WXPublicUserVo wxPublicUserVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return publicUserService.updateUser(wxPublicUserVo);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info/{openId}")
    public MyResponse info(@PathVariable String openId) {
        if (StringUtils.isEmpty(openId)) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        PublicUser publicUser = new PublicUser();
        publicUser.setOpenId(openId);
        QueryWrapper<PublicUser> queryWrapper = new QueryWrapper<>(publicUser);
        publicUser = publicUserService.getOne(queryWrapper);
        WXPublicUserVo wxPublicUserVo = new WXPublicUserVo();
        Picture picture = null;
        if (ObjectUtils.isNotEmpty(publicUser)) {
            String pictureId = publicUser.getPictureId();
            if (StringUtils.isNotEmpty(pictureId)) {
                picture = pictureService.getById(pictureId);
            }
            try {
                BeanUtils.copyProperties(wxPublicUserVo, publicUser);
            } catch (Exception e) {
                log.error("BeanUtils.copyProperties error ", e);
            }
        }
        wxPublicUserVo.setPicture(picture);
        return MyResponse.success(wxPublicUserVo);
    }

    /**
     * 搜索业主（访客来访问业主时 全匹配搜索 返回信息 手机号中间4位加密）
     */
    @PostMapping("/findOwner")
    public MyResponse findOwner(@RequestBody FindOwnerDto findOwnerDto) {
        if (ObjectUtils.isEmpty(findOwnerDto)) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return publicUserService.findOwner(findOwnerDto);
    }

    /**
     * fixme 給管理員账号绑定微信公众号 暂时废弃 因为绑定上也没用 还需要维护
     * 根据姓名搜索用户 返回头像
     */
    @PostMapping("/queryToBind")
    public LayuiPage queryToBind(@RequestBody PageRequest<PublicUserCondition> pageRequest) {
        if (ObjectUtils.isEmpty(pageRequest) ||
                pageRequest.getCondition() == null ||
                pageRequest.getCondition().getName() == null) {
            return new LayuiPage(new ArrayList<>());
        }
        List<PublicUserVo> publicUsers = publicUserService.queryToBind(pageRequest);
        return LayuiPage.parsePage(publicUsers);
    }

    /**
     * fixme 給管理員账号绑定微信公众号 暂时废弃 因为绑定上也没用 还需要维护
     * 将用户绑定到管理员账号
     */
    @PostMapping("/bindToWx")
    public MyResponse bindToWx(@RequestBody BindToWxDto bindToWxDto) {
        if (ObjectUtils.isEmpty(bindToWxDto)) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return publicUserService.bindToWx(bindToWxDto);
    }

    /*-----------------------------------------------------------------------------*/

    /**
     * 获取当前小区下用户权限
     */
    @PostMapping("/getUserPermission")
    public LayuiPage getUserPermission(@RequestParam(required = false) String communityId,
                                       @RequestParam String openId, HttpSession session) {
        if (session != null) {
            String sessionCommunityId = (String) session.getAttribute("communityId");
            if (sessionCommunityId != null) {
                communityId = sessionCommunityId;
            }
        }
        List<UserPermissionDto> list = publicUserService.getUserPermission(communityId, openId);
        if (CollectionUtils.isEmpty(list)) {
            return LayuiPage.parsePage(new ArrayList<>());
        }
        return LayuiPage.parsePageAll(list);
    }

}
